<template>
  <div class="app-container">
    <el-dialog :title="title" :visible.sync="formVisible" append-to-body width="500px">
      <el-form ref="myForm" :model="form" label-width="100px">
        <el-form-item label="角色名称" required prop="name">
          <el-input v-model="form.name" placeholder="角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" required prop="description">
          <el-input v-model="form.description" placeholder="角色描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="allotVisible" append-to-body width="500px">
      <el-form :model="allotForm" label-width="100px">
        <el-form-item label="分配权限" required>
          <el-select
            v-model="allotForm.permissionIds"
            multiple
            placeholder="请选择权限"
            style="width:100%"
          >
            <el-option
              v-for="p in permissionList"
              :key="p.id"
              :label="p.description"
              :value="p.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="allotVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitAllot">提交</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="allotMenusVisible" title="角色菜单" :visible.sync="allotMenusVisible">
      <el-form :model="allotMenuForm" label-width="100px">
        <el-form-item label="分配菜单">
          <el-tree
            ref="menusTree"
            :check-strictly="true"
            :data="treeMenus"
            show-checkbox
            :props="{label: 'name'}"
            node-key="id"
            default-expand-all
            :default-checked-keys="allotMenuForm.menuIds"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmitAllotMenu">确认分配</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-form :inline="true" size="small">
      <el-form-item label="搜索:">
        <el-input v-model="searchParams.search" placeholder="请输入搜索内容" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="fetchData">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-circle-plus" @click="handleInsert">添加角色</el-button>
      </el-form-item>
    </el-form>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID">
        <template slot-scope="scope">{{ scope.row.id }}</template>
      </el-table-column>
      <el-table-column align="center" label="角色名称">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column align="center" label="角色描述">
        <template slot-scope="scope">{{ scope.row.description }}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <template slot-scope="scope">
          <el-button type="text" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-lock"
            @click="handleAllot(scope.row)"
          >分配权限</el-button>
          <el-button
            type="text"
            size="mini"
            icon="el-icon-menu"
            @click="handleAllotMenu(scope.row)"
          >分配菜单</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div :style="{textAlign:'center',padding:'10px'}">
      <el-pagination
        background
        :current-page.sync="searchParams.pageNum"
        :page-sizes="[10, 20, 30, 40,50]"
        :page-size.sync="searchParams.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="searchParams.total"
        @size-change="fetchData"
        @current-change="fetchData"
      />
    </div>
  </div>
</template>

<script>
import { roleList, delRole, saveRole } from '@/api/system/role'
import { permissionList } from '@/api/system/permission'
import {
  getRolePermissions,
  allotRolePermissions
} from '@/api/system/role_permission'
import { getRoleMenus, getTreeMenus, allotRoleMenus } from '@/api/system/menu'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      formVisible: false,
      form: {},
      allotForm: {},
      allotMenuForm: {},
      allotVisible: false,
      allotMenusVisible: false,
      permissionList: [],
      treeMenus: [],
      searchParams: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        search: ''
      },
      title: ''
    }
  },
  created() {
    this.fetchData()
    permissionList().then(res => {
      this.permissionList = res.data.records
    })
    getTreeMenus().then(res => {
      this.treeMenus = res.data
    })
  },
  methods: {
    handleSubmitAllotMenu() {
      this.$confirm('确认为此角色分配菜单吗？', '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确认'
      }).then(() => {
        const data = this.$refs.menusTree
          .getCheckedNodes()
          .map(item => item.id)
        allotRoleMenus({
          roleId: this.allotMenuForm.roleId,
          menuIds: data
        }).then(() => {
          this.$message.success('分配菜单成功')
          this.fetchData()
          this.allotMenusVisible = false
        })
      })
    },
    handleSubmitAllot() {
      this.$confirm('确认为此角色分配权限吗？', '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确认'
      }).then(() => {
        allotRolePermissions(this.allotForm).then(() => {
          this.$message.success('分配权限成功')
          this.fetchData()
          this.allotVisible = false
        })
      })
    },
    handleAllot(row) {
      getRolePermissions(row.id).then(res => {
        const permissionIds = res.data
        this.allotForm = {
          roleId: row.id,
          permissionIds
        }
        this.allotVisible = true
        this.title = '分配角色权限'
      })
    },
    handleAllotMenu(row) {
      getRoleMenus(row.id).then(res => {
        const menuIds = res.data
        this.allotMenuForm = {
          roleId: row.id,
          menuIds
        }
        this.allotMenusVisible = true
      })
    },
    handleUpdate(row) {
      this.form = { ...row }
      this.formVisible = true
      this.title = '修改角色信息'
    },
    handleInsert() {
      this.formVisible = true
      this.title = '添加角色信息'
      this.$nextTick(() => {
        this.$refs['myForm'].resetFields()
        this.form = {}
      })
    },
    handleSubmit() {
      this.$refs['myForm'].validate(valid => {
        if (valid) {
          saveRole(this.form).then(() => {
            this.$message.success('保存信息成功')
            this.fetchData()
            this.formVisible = false
          })
        }
      })
    },
    handleDelete({ id }) {
      this.$confirm('确认删除此信息吗？', '警告', {
        cancelButtonText: '取消',
        confirmButtonText: '确认'
      }).then(() => {
        delRole(id).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        })
      })
    },
    fetchData() {
      this.listLoading = true
      roleList(this.searchParams).then(response => {
        const { records, total } = response.data
        this.list = records
        this.searchParams.total = total
        this.listLoading = false
      })
    }
  }
}
</script>

